<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" label-width="120px">
          <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button   @click="close">关闭</el-button>
          </el-form-item>
          <h4>打印配置</h4>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-tooltip content="纸张的宽度，单位:毫米" placement="top">
                <el-form-item label="纸张的宽度">
                  <el-input-number v-model="printSetButton.printerPageWidth"  :min="1" :max="99999" label=""></el-input-number>
                </el-form-item>
              </el-tooltip>
            </el-col>
            <el-col :span="24">
              <el-tooltip content="纸张的高度，单位:毫米" placement="top">
                <el-form-item label="纸张高度">
                  <el-input-number v-model="printSetButton.printerPageHeight"  :min="1" :max="99999" label=""></el-input-number>
                </el-form-item>
              </el-tooltip>
            </el-col>

            <el-col :span="24">
              <el-tooltip content="每页数量" placement="top">
                <el-form-item label="每页数量">
                  <el-input-number v-model="printSetButton.printerPageSize"  :min="1" :max="99999" label=""></el-input-number>
                </el-form-item>
              </el-tooltip>
            </el-col>

          </el-row>
        </el-form>
      </el-col>
      <el-col :span="18">
        <h4>打印列配置</h4>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="使用视图">
            <FortenDataviewDown
              propDownType="form"
              :propFlagDialog="false"
              propFieldText="viewKey"
              propClickType="input"
              :propForm="printSetButton"
              :propTableQueries="$newWrapper().ne('view_type', 'import')"
              :propPK="printSetButton.viewKey"
              :propUserParam="{viewKey: 'system_dv_define',useMsg: '请选择视图'}"
              @select-change="selectChangeImport"
            ></FortenDataviewDown>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="getPrintColumns">更新打印列字段</el-button>
          </el-form-item>
        </el-form>

        <FortenVxetableStatic :data="data" :columns="tableColumns" :maxHeight="maxHeight" :btnList="btnList" @userFun="userFun" pkName="name"
                              :searchFieldArr="['name','title']"
                              searchPlaceholder="搜索字段名/显示名"
                              :defaultSort="defaultSort"
                              :buttonList="buttonList"
                              :disabled="disabled"
                              @cellChange="cellChange"

        ></FortenVxetableStatic>

      </el-col>
    </el-row>
  </div>
</template>

<script>
/* eslint-disable*/
import FortenVxetableStatic from '@/components/common/FortenVxetableStatic.vue'


export default {
  title:'数据视图维护网格列',
  props:['data',  'propParent', 'printSetButton', 'disabled'],
  components: {
    FortenVxetableStatic
  },
  mounted() {
    this.init()
  },
  data() {
    return {
      formInline: {},
      //字段列表
      tableColumns: [],
      //按钮列表
      btnList: [{
        key: 'delete',
        icon: 'el-icon-delete',
        size: 'mini',
        style: {padding: '6px'},
        type: 'danger',
        title: '移除该列'
      }],
      maxHeight: window.innerHeight - 200,

      //默认排序
      defaultSort: {
        field: 'printSort',
        order: 'asc',
      },

      buttonList: [
      ]
    }
  },
  methods: {
    //初始化操作
    init() {
      //列配置
      this.tableColumns = [
        {field: 'name', title: '字段名', minWidth: 120, fixed: 'left', titleHelp: '数据字段名称'},
        {
          minWidth: 120,
          field: 'title',
          title: '打印列名',
          editRender: {name: 'ElInput', attrs: {type: 'text'}},
          fixed: 'left',
          titleHelp: '列的显示名称',
          //表头列按钮
          headBtnList: [
            {
              key: 'setPrintTitleIfnull',
              size: 'mini',
              style: {padding: '2px'},
              type: 'danger',
              title: '将所有为空的打印列名设置为网格列名称',
              text: '设置为空的打印列名称'
            }
          ],
        },
        {
          field: 'noprint',
          title: '不打印',
          minWidth: 80,
          editRender: {name: 'ElSwitch'},
          formatter: 'formatSwitch',
          titleHelp: '不打印该字段',
          filter: true,
          formatter: 'formatSwitch',
          //表头列按钮
          headBtnList: [
            {
              key: 'setNoprintIfnull',
              size: 'mini',
              style: {padding: '2px'},
              type: 'danger',
              title: '将所有字段都设置不打印',
              text: '全部设置不打印'
            }
          ],
        },
        {
          field: 'flagSumBottom',
          title: '显示底部总合计',
          minWidth: 80,
          editRender: {name: 'ElSwitch'},
          formatter: 'formatSwitch',
          titleHelp: '选中后，底部将显示多所有数据的数值类型的汇总',
          filter: true,
        },
        {
          field: 'printIndex',
          title: '排序',
          minWidth: 80,
          editRender: {name: 'ElInputNumber', attrs: {min: 0, max: 999}},
          titleHelp: '打印列排序，不指定则为999',
          //表头列按钮
          headBtnList: [
            {
              key: 'setPrintIndexIfnull',
              size: 'mini',
              style: {padding: '2px'},
              type: 'danger',
              title: '将所有为空的排序设置为网格列排序',
              text: '设置为空的排序'
            }
          ],

          //变化后进行排序，比如改了顺序
          changeSort: true,
          sortable: true,
        },
        {
          field: 'width',
          title: '宽度',
          minWidth: 80,
          editRender: {name: 'ElInput', attrs: {type: 'text'}},
          titleHelp: '列表显示宽度，可设置为数字或者auto，不填的话为auto'
        },
        {
          minWidth: 120,
          field: 'printEval',
          title: '表达式',
          editRender: {name: 'ElInput', attrs: {type: 'text'}},
          titleHelp: 'EVAL表达式显示，将使用eval转换，局部变量row，为数据行对象比如： row.skuQty + row.skuUnit',
        },
      ]
    },

    //回调函数
    userFun({config, scope}) {
      switch (config.key) {
        case 'setNoprintIfnull': //将所有字段都设置不打印
          this.data.forEach(column => {
            this.$set(column,'noprint',true)
          })
          break
        case 'setPrintTitleIfnull': //将所有为空的打印列名设置为网格列名称
          this.data.forEach(column => {
            if (this.strings.isBlank(column.printTitle)) this.$set(column,'printTitle',column.title)
          })
          break
        case 'setPrintIndexIfnull': //将所有为空的排序设置为网格列排序
          this.data.forEach(column => {
            if (this.strings.isBlank(column.printIndex)) this.$set(column,'printIndex',column.sort)
          })
          break
      }
    },

    getPrintColumns(){
      this.$confirm('是否更新打印列字段，将将根据所选择视图网格列中不存在的字段添加到打印列中?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this._getPrintColumns()
      }).catch(() => {
      })
    },

    //保存
    save() {
      this.data.sort((left, right) => {
        return this.strings.defaultIfBlank(left.printIndex, 999) - this.strings.defaultIfBlank(right.printIndex, 999)
      })

      this.printSetButton.printColumns = this.data
      this.propParent.ocAsynSaveViewForm()
    },
    //关闭
    close() {
      this.$emit('close')
    },

    //更新打印列字段，将网格列中不存在的字段添加到打印列中
    async _getPrintColumns() {

      if (!this.data || this.data.length < 1) {
        this.data = []
      }
      if (this.strings.isBlank(this.printSetButton.viewKey)) {
        this.utilMessage.warning('请先选择数据视图')
        return
      }
      let columns = []
      const params = {
        viewKey: this.printSetButton.viewKey
      }
      this.utilVue.loadShow(true)
      await this.$ajax.get('data-view/find', {params}).then(resp => {
        if (resp.code != 0) {
          global.utilMessage.alertFail(`获取视图结构发生错误：${resp.msg}`)
          return
        }
        columns = resp.data.view.columns
        this.utilVue.loadHide(true)
      })

      let columnAdd = []
      let columnNameAdd = []
      columns.forEach(item => {
        const findIndex = this.data.findIndex(col => col.name === item.name)
        if (findIndex < 0) {
          columnAdd.push(JSON.parse(JSON.stringify(item)))
          columnNameAdd.push(item.name)
        }
      })

      let columnDelete = []
      let columnDeleteNameAdd = []
      this.data.forEach(item => {
        const findIndex = columns.findIndex(col => col.name === item.name)
        if (findIndex < 0) {
          columnDelete.push(JSON.parse(JSON.stringify(item)))
          columnDeleteNameAdd.push(item.name)
        }
      })

      //新增字段
      if (columnNameAdd.length > 0) {
        let msg = `
                    <div  style="word-break: break-all; max-height: 100px; max-width: 200px; overflow: auto;">${columnNameAdd.join(',')}
                    </div>
`
        await this.$confirm(msg, '打印列新增字段，是否执行？', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          columnAdd.forEach(column => {
            this.data.push(column)
          })
        }).catch(() => {
        })
      }

      //网格列变化  -- 删除字段
      if (columnDeleteNameAdd.length > 0) {
        let msg = `
                    <div  style="word-break: break-all; max-height: 100px; max-width: 200px; overflow: auto;">${columnDeleteNameAdd.join(',')}
                    </div>
`

        await this.$confirm(msg, '打印列删除字段，是否执行？', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          columnDeleteAdd.forEach(column => {
            let columnIndex = this.data.findIndex(column2 => column2.name == column.name )
            if (columnIndex != -1) this.data.splice(columnIndex, 1)
          })
        }).catch(() => {
        })
      }
    },

    //输入改变
    cellChange() {
    },
    //视图选择后
    selectChangeImport({fieldText, row, propPK, that}) {
      this.$set(this.printSetButton,'viewKey', row.viewKey)
    },
  }
}
</script>

<style lang="scss" scoped>
  .container{
    height: auto !important;
    padding: 5px;
  }
</style>
